#include "e2d/core/physics/RigidbodyStatic.h"
#include "e2d/core/physics/PxUtils.h"
#include "e2d/core/trans/TransformNode.h"
#include "e2d/core/Entity.h"

using namespace physx;

void e2d::RigidbodyStatic::OnLoad()
{
	Delete();
	Create();

	auto& scene = e2d::PxUtils::gScene;
	auto& physics = e2d::PxUtils::gPhysics;

}



void e2d::RigidbodyStatic::Delete()
{
	auto& scene = e2d::PxUtils::gScene;
	auto& physics = e2d::PxUtils::gPhysics;

	if (m_PxRgStatic)
	{
		scene->removeActor(*m_PxRgStatic);
		m_PxRgStatic->release();
		m_PxRgStatic = 0;
	}

	m_PxShapeMaps.Delete();

}
void e2d::RigidbodyStatic::Create()
{
	Delete();

	auto& scene = e2d::PxUtils::gScene;
	auto& physics = e2d::PxUtils::gPhysics;

	if (m_PxRgStatic)
	{
		scene->removeActor(*m_PxRgStatic);
		m_PxRgStatic->release();
		m_PxRgStatic = 0;
	}

	const auto& transformNode = m_Entity->GetConst<e2d::TransformNode>();
	m_PxRgStatic = physics->createRigidStatic(e2d::PxUtils::toPxTransform(transformNode.m_World));
	scene->addActor(*m_PxRgStatic);

	m_PxShapeMaps.Create();
	m_PxShapeMaps.AttachedToRigidBody(m_PxRgStatic);


}
void e2d::RigidbodyStatic::OnStart()
{
}

void e2d::RigidbodyStatic::OnUpdate()
{
}

void e2d::RigidbodyStatic::OnUpdateRuntime()
{
	if (m_PxRgStatic == 0)
	{
		return;
	}
	auto& transformNode = m_Entity->Get<e2d::TransformNode>();

	const auto pxTransform = m_PxRgStatic->getGlobalPose();

	auto pullTransform = e2d::PxUtils::toGlmTransform(pxTransform);
	auto originScale = transformNode.m_World.m_Scale;
	pullTransform.m_Scale = originScale;

	transformNode.SetWorldTransform(pullTransform);
	transformNode.m_Local.Fixed();


}

void e2d::RigidbodyStatic::OnDestroy()
{
}
